---
interface Props {
  content: string
}

const { content } = Astro.props
---

<section
  class="mermaid"
  data-content={content}
>
</section>

<script>
import { onThemeChange } from "#/lib/on-theme-change"
import mermaid from "mermaid"

const initialTheme = document.documentElement.getAttribute("data-theme") as "dark" | "light"

async function renderDiagrams({
  graphs,
  theme,
}: {
  graphs: HTMLCollectionOf<Element>
  theme: "dark" | "light"
}): Promise<void> {
  mermaid.initialize({
    // keep false otherwise it sometimes breaks the rendering
    startOnLoad: false,
    fontFamily: "var(--sans-font)",
    theme: theme === "dark" ? "dark" : "default",
  })

  for (const graph of graphs) {
    const content = graph.getAttribute("data-content")
    if (!content) {
      continue
    }
    let svg = document.createElement("svg")
    const id = (svg.id = "mermaid-" + Math.round(Math.random() * 100000))
    graph.appendChild(svg)
    mermaid.render(id, content).then(result => {
      graph.innerHTML = result.svg
    })
  }
}
const graphs = document.getElementsByClassName("mermaid")
if (graphs.length > 0) {
  renderDiagrams({ graphs, theme: initialTheme })
}

onThemeChange(newTheme => {
  renderDiagrams({ graphs, theme: newTheme })
})
</script>
